//
//  MaintainViewController.m
//  StationManager
//
//  Created by Helong on 17/3/3.
//  Copyright © 2017年 Helong. All rights reserved.
//

#import "MaintainViewController.h"
#import "UnNormalTableView.h"
#import "NormalTableView.h"
#import <ZipArchive.h>
#import <MBProgressHUD.h>
#import <AFNetworking/AFNetworking.h>
#import "AFNwebManager.h"

@interface MaintainViewController ()<UIScrollViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,openPickerDelegate>

//是否保存了信息
@property (assign,nonatomic) BOOL isSaved;
//背景View
@property (strong,nonatomic) UIView * bgView;
//顶部背景View
@property (strong,nonatomic) UIView * topView;
//图片的tag值
@property (assign,nonatomic) NSInteger cellTag;
//下划线
@property (strong,nonatomic) UILabel * baseLine;
//底部背景View
@property (strong,nonatomic) UIView * bottomView;
//压缩图片
@property (strong,nonatomic) ZipArchive * zipper;
//弹出提示
@property (strong,nonatomic) MBProgressHUD * hud;
//上传的数据
@property (strong,nonatomic) NSString * uploadData;
//保存按钮Button
@property (strong,nonatomic) UIButton * saveButton;
//常用信息按钮Button
@property (strong,nonatomic) UIButton * normalButton;
//提交按钮Button
@property (strong,nonatomic) UIButton * submitButton;
//ScrollView
@property (strong,nonatomic) UIScrollView * scrollView;
//不常用信息按钮Button
@property (strong,nonatomic) UIButton * unNormalButton;
//上传文件进度条
@property (strong,nonatomic) UIProgressView * progressView;
//图片选择器
@property (strong,nonatomic) UIImagePickerController * picker;
//常用信息数据列表TableView
@property (strong,nonatomic) NormalTableView * normalTableView;
//不常用信息数据列表TableView
@property (strong,nonatomic) UnNormalTableView *unNormalTableView;
@end

@implementation MaintainViewController





- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"维护记录表";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.cellTag = 99;
    self.isSaved = NO;
    NSLog(@"type:%@",_stationModel.stationType);
     NSLog(@"CurrentTime:%@",_currentTime);
   NSLog(@"status:%@",_stationModel.stationStatus);
     [self setUI];
}

//搭建界面UI
- (void)setUI {
    
    _topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    _topView.backgroundColor = [UIColor colorWithRed:34/255.0 green:150/255.0 blue:243/255.0 alpha:1.0];
    [self.view addSubview:_topView];
    
    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-104, SCREEN_WIDTH, 40)];
    _bottomView.backgroundColor = [UIColor colorWithRed:34/255.0 green:150/255.0 blue:243/255.0 alpha:1.0];
    [self.view addSubview:_bottomView];
    
    _normalButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _normalButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [_normalButton setTitle:@"常用信息" forState:UIControlStateNormal];
    _normalButton.backgroundColor = [UIColor whiteColor];
    [_normalButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_normalButton setTitleColor:[UIColor colorWithRed:34/255.0 green:150/255.0 blue:243/255.0 alpha:1.0] forState:UIControlStateSelected];
    [_normalButton addTarget:self action:@selector(normalClick) forControlEvents:UIControlEventTouchUpInside];
    _normalButton.selected = YES;
    [_topView addSubview:_normalButton];
    
    [_normalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.top.equalTo(@0);
        make.width.mas_equalTo(SCREEN_WIDTH/2);
        make.height.mas_equalTo(39);
    }];
    
    _unNormalButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _unNormalButton.backgroundColor = [UIColor whiteColor];
    [_unNormalButton setTitle:@"不常用信息" forState:UIControlStateNormal];
    _unNormalButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [_unNormalButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_unNormalButton setTitleColor:[UIColor colorWithRed:34/255.0 green:150/255.0 blue:243/255.0 alpha:1.0] forState:UIControlStateSelected];
    [_unNormalButton addTarget:self action:@selector(unNormalClick) forControlEvents:UIControlEventTouchUpInside];
    [_topView addSubview:_unNormalButton];
    
    [_unNormalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.normalButton.mas_right);
        make.top.equalTo(@0);
        make.width.mas_equalTo(SCREEN_WIDTH/2);
        make.height.mas_equalTo(39);
    }];
    
    _baseLine = [[UILabel alloc]init];
    _baseLine.backgroundColor = [UIColor colorWithRed:34/255.0 green:150/255.0 blue:243/255.0 alpha:1.0];
    [_topView addSubview:_baseLine];
    [_baseLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.top.equalTo(self.normalButton.mas_bottom).offset(-2);
        make.width.mas_equalTo(SCREEN_WIDTH/2);
        make.height.mas_equalTo(3);
    }];
    
    _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
    _submitButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [_submitButton addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_submitButton];
    _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
    _saveButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [_saveButton addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_saveButton];
    
    _scrollView = [[UIScrollView alloc] init];
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*2, 0);
    _scrollView.bounces = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.backgroundColor = WHITECOLOR;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    
    _normalTableView = [[NormalTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-145) style:UITableViewStyleGrouped];
    _normalTableView.stationModel = self.stationModel;
    _normalTableView.currentTime = _currentTime;
    [_normalTableView setImageData];
    _normalTableView.pickDelegate = self;
    [_scrollView addSubview:_normalTableView];
    _unNormalTableView = [[UnNormalTableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT-145) style:UITableViewStyleGrouped];
    NSDictionary * dict = [self jsonDict];
    
    if ([self.stationModel.stationType isEqualToString:@"T1"]) {
        _unNormalTableView.unNormalOrigin =dict[@"origin"][@"storm"];
        [_unNormalTableView.unNormalArray addObjectsFromArray:_unNormalTableView.unNormalOrigin];
        _unNormalTableView.textArray =dict[@"headText"][@"storm"];
    }
    else if ([self.stationModel.stationType isEqualToString:@"T2"] || [self.stationModel.stationType isEqualToString:@"G2"]) {
        _unNormalTableView.unNormalOrigin =dict[@"origin"][@"twoFactor"];
        [_unNormalTableView.unNormalArray addObjectsFromArray:_unNormalTableView.unNormalOrigin];
        _unNormalTableView.textArray =dict[@"headText"][@"twoFactor"];
    }
    else {
        _unNormalTableView.unNormalOrigin =dict[@"origin"][@"fourFactor"];
        [_unNormalTableView.unNormalArray addObjectsFromArray:_unNormalTableView.unNormalOrigin];
        _unNormalTableView.textArray =dict[@"headText"][@"fourFactor"];
    }
    
    _unNormalTableView.stationType = self.stationModel.stationType;
    _unNormalTableView.delegate = _unNormalTableView;
    _unNormalTableView.dataSource = _unNormalTableView;
    [_scrollView addSubview:_unNormalTableView];
    
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.top.equalTo(@5);
        make.bottom.equalTo(@-5);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(30);
    }];
    
    [_saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-20);
        make.top.equalTo(@5);
        make.bottom.equalTo(@-5);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(30);
    }];
    
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
}

//解析本地json数据
- (NSDictionary *)jsonDict {
    
    NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Maintenance" ofType:@"json"];
    NSData * jsonData = [[NSData alloc]initWithContentsOfFile:filePath];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    NSDictionary * dict = jsonObject[@"unNormal"];
    return dict;
}

#pragma ScrollView - delegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    int i = scrollView.contentOffset.x/SCREEN_WIDTH;
    if (i == 0) {
        _normalButton.selected = YES;
        _unNormalButton.selected = NO;
        [UIView animateWithDuration:0.1 animations:^{
            _baseLine.frame = CGRectMake(0, 37, SCREEN_WIDTH/2, 3);
        }];
        
    }else{
        _normalButton.selected = NO;
        _unNormalButton.selected = YES;
        
        [UIView animateWithDuration:0.1 animations:^{
            _baseLine.frame = CGRectMake(SCREEN_WIDTH/2, 37, SCREEN_WIDTH/2, 3);
        }];
    }
}

//点击常用信息按钮
- (void)normalClick {
    
    _normalButton.selected = YES;
    _unNormalButton.selected = NO;
    _baseLine.backgroundColor = [UIColor colorWithRed:34/255.0 green:150/255.0 blue:243/255.0 alpha:1.0];
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.contentOffset = CGPointMake(0, 0);
        _baseLine.frame = CGRectMake(0, 37, SCREEN_WIDTH/2, 3);
    }];
}

//点击不常用信息按钮
- (void)unNormalClick {
    
    _unNormalButton.selected = YES;
    _normalButton.selected = NO;
    _baseLine.backgroundColor = [UIColor colorWithRed:34/255.0 green:150/255.0 blue:243/255.0 alpha:1.0];
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
        _baseLine.frame = CGRectMake(SCREEN_WIDTH/2, 37, SCREEN_WIDTH/2, 3);
    }];
}

//点击提交按钮
- (void)submitClick {
    
    if (_normalTableView.headView.personTextField.text.length == 0 || [_normalTableView.photoTagArray containsObject:@-1] ){
        
        [self showAlert:@"请填写维护人员和添加图片" duration:1.5 IsSubmited:NO];
        self.isSaved = NO;
        
    }else if ([_normalTableView.headView.personTextField.text hasPrefix:@" "] || [_normalTableView.photoTagArray containsObject:@-1]) {
        
        [self showAlert:@"请填写维护人员和添加图片" duration:1.5 IsSubmited:NO];
        self.isSaved = NO;
        
    }else{
        
        NSString *strPath=[NSString stringWithFormat:@"%@/Documents/taizhan",NSHomeDirectory()];
        NSArray *documentList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strPath error:nil];
        for (NSInteger i=0; i<documentList.count; i++) {
            if ([documentList[i] hasPrefix:_stationModel.stationName]) {
                [[NSFileManager defaultManager]  removeItemAtPath:[NSString stringWithFormat:@"%@/%@",strPath,documentList[i]] error:nil];
            }
        }
        
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYYMMddHHmmss"];
        NSString * dateTime = [formatter stringFromDate:date];
        
        NSString *strGeneralPath=[NSString stringWithFormat:@"%@/Documents/taizhan",NSHomeDirectory()];
        [[NSFileManager defaultManager] createDirectoryAtPath:strGeneralPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",strGeneralPath);
        
        NSString *strFinalPath=[NSString stringWithFormat:@"%@/%@%@",strGeneralPath,_stationModel.stationName,dateTime];
        [[NSFileManager defaultManager] createDirectoryAtPath:strFinalPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",strFinalPath);
        
        NSString * filePath = [NSString stringWithFormat:@"%@/%@%@.txt",strFinalPath,self.stationModel.stationName,dateTime];
        NSFileManager *fileManager =[NSFileManager defaultManager];
        NSArray * titleArray = @[@"先前状态：",@"运维措施：",@"运维结果："];
        NSArray * firstArray = @[@"蓄电池",@"采集器"];
        NSString * unNormalData = @"";
        NSString * normalData = @"";
        for (NSInteger i=0; i<_unNormalTableView.unNormalArray.count; i++) {
            for (NSInteger j = 0; j<[_unNormalTableView.unNormalArray[i] count]; j++) {
                unNormalData = [unNormalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",[_unNormalTableView.textArray[i] substringFromIndex:2],titleArray[j],_unNormalTableView.unNormalArray[i][j]]];
            }
        }
        for (NSInteger i=0; i<_normalTableView.dataArray.count; i++) {
            for (NSInteger j=0; j<[_normalTableView.dataArray[i] count]; j++) {
                
                if (i == 0&&j == 0) {
                    normalData = [normalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",firstArray[i],titleArray[j],_normalTableView.batteryTextField.text]];
                }else if (i == 1&&j == 0){
                    normalData = [normalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",firstArray[i],titleArray[j],_normalTableView.signalTextField.text]];
                }else{
                    normalData = [normalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",firstArray[i],titleArray[j],_normalTableView.dataArray[i][j]]];
                }
            }
        }
        
        
        if ([_stationModel.stationStatus isEqualToString:@"0"]||[_stationModel.stationStatus isEqualToString:@"3"]) {
            
            _uploadData = [NSString stringWithFormat:@"任务类型：2"];
            
        }
        else{
            _uploadData = [NSString stringWithFormat:@"任务类型：1"];
        }
        _uploadData = [NSString stringWithFormat:@"%@\r\n%@%@\r\n台站号：%@\r\n%@%@\r\n%@%@\r\n%@%@备注：%@\r\n图片：",_uploadData,_normalTableView.headView.nameLabel.text,_normalTableView.headView.stationName.text,_normalTableView.headView.stationNumber.text,_normalTableView.headView.datelabel.text,_normalTableView.headView.dateTimeLabel.text,_normalTableView.headView.personlabel.text,_normalTableView.headView.personTextField.text,normalData,unNormalData,_normalTableView.remarkTextField.text];
        
        for (NSInteger i = 0; i<_normalTableView.photoTagArray.count; i++) {
            if ([_normalTableView.photoTagArray[i] integerValue]!=-1) {
                
                NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
                
                NSString * imageString = [NSString stringWithFormat:@"%.f.JPEG|",interval];
                [_uploadData stringByAppendingString:imageString];
                _uploadData = [NSString stringWithFormat:@"%@%@",_uploadData,imageString];
                
                UIImage * originImage = _normalTableView.photoArray[i];
                if (originImage.size.width>=originImage.size.height) {
                    [UIImageJPEGRepresentation([self OriginImage:originImage scaleToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT/2)], 1.0)writeToFile: [NSString stringWithFormat:@"%@/%.f.JPEG",strFinalPath,interval] atomically:YES];
                }else{
                    [UIImageJPEGRepresentation([self OriginImage:originImage scaleToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)], 1.0)writeToFile: [NSString stringWithFormat:@"%@/%.f.JPEG",strFinalPath,interval] atomically:YES];
                }
                
            }
        }
        _uploadData = [NSString stringWithFormat:@"%@\r\n图片类型：",_uploadData];
        for (NSInteger i = 0; i<_normalTableView.photoTagArray.count; i++) {
            if ([_normalTableView.photoTagArray[i] integerValue]!=-1) {
                
                NSString * typeString = [NSString stringWithFormat:@"%@|",_normalTableView.titleArray[i]];
                [_uploadData stringByAppendingString:typeString];
                
                _uploadData = [NSString stringWithFormat:@"%@%@",_uploadData,typeString];
                
            }
        }
        _zipper = [[ZipArchive alloc]init];
        [_zipper CreateZipFile2:[NSString stringWithFormat:@"%@/%@%@.zip",strFinalPath,_stationModel.stationName,dateTime]];
        
        NSArray *fileList = [fileManager contentsOfDirectoryAtPath:strFinalPath error:nil];
        for (NSInteger i=0; i<fileList.count; i++) {
            
            NSString * str = [fileList[i] substringFromIndex:[fileList[i] length]-4];
            if ([str isEqualToString:@"JPEG"]) {
                [_zipper addFileToZip:[NSString stringWithFormat:@"%@/%@",strFinalPath,fileList[i]] newname:fileList[i]];
                [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",strFinalPath,fileList[i]] error:nil];
            }
        }
        [_zipper CloseZipFile2];
        
       
        [fileManager createFileAtPath:filePath contents:[_uploadData dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

        
        _bgView = [[UIView alloc]init];
        _bgView.backgroundColor = [UIColor blackColor];
        _bgView.alpha = 0.8;
        [self.view addSubview:_bgView];
        
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@50);
            make.top.equalTo(_topView.mas_bottom).offset(120);
            make.right.equalTo(@-50);
            make.height.mas_equalTo(50);
        }];
        
        _progressView = [[UIProgressView alloc]init];
        _progressView.progress=0.0;
        [_bgView addSubview:_progressView];
        
        [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@5);
            make.top.equalTo(@5);
            make.right.equalTo(@-5);
            make.height.mas_equalTo(10);
        }];
        
        UILabel * foldSizeLabel = [[UILabel alloc]init];
        foldSizeLabel.backgroundColor = [UIColor blackColor];
        foldSizeLabel.font = [UIFont systemFontOfSize:11.0];
        foldSizeLabel.textAlignment = NSTextAlignmentCenter;
        foldSizeLabel.textColor = [UIColor whiteColor];
        [_bgView addSubview:foldSizeLabel];
        
        UILabel * uploadSizeLabel = [[UILabel alloc]init];
        uploadSizeLabel.backgroundColor = [UIColor blackColor];
        uploadSizeLabel.font = [UIFont systemFontOfSize:11.0];
        uploadSizeLabel.textAlignment = NSTextAlignmentCenter;
        uploadSizeLabel.textColor = [UIColor whiteColor];
        [_bgView addSubview:uploadSizeLabel];
        
        [foldSizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(@-5);
            make.top.equalTo(_progressView.mas_bottom).offset(5);
            make.width.mas_equalTo(80);
            make.height.mas_equalTo(20);
        }];
        
        [uploadSizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@5);
            make.top.equalTo(_progressView.mas_bottom).offset(5);
            make.width.mas_equalTo(80);
            make.height.mas_equalTo(20);
        }];
        
//        NSString *strPath=[NSString stringWithFormat:@"%@/Documents/taizhan",NSHomeDirectory()];
        NSString *txtDocuments;
        NSString *zipDocuments;
        NSString *foldDocuments;

        NSArray *fileList1 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@",strPath] error:nil];
        for (NSString * documents in fileList1) {
            
            if ([documents hasPrefix:_normalTableView.headView.stationName.text]) {
                
                foldDocuments = documents;
                NSArray * list = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/%@",strPath,foldDocuments] error:nil];
                for (NSString * foldNames in list) {
                    
                    if ([foldNames hasSuffix:@".txt"]) {
                        
                        txtDocuments = foldNames;
                    }
                    if ([foldNames hasSuffix:@".zip"]) {
                        zipDocuments = foldNames;
                    }
                }
            }
        }
        foldSizeLabel.text = [NSString stringWithFormat:@"总共：%.2fM",[self folderSizeAtPath:[NSString stringWithFormat:@"%@/%@",strPath,foldDocuments]]];
        AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             @"text/plain",
                                                             @"video/mp4",
                                                             @"application/gzip",
                                                             nil];
        
        NSURLSessionDataTask *task = [manager POST:@"http://192.168.0.77:8080/Phone/upload.aspx" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
            
            [formData appendPartWithFileData:[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@",strPath,foldDocuments,txtDocuments]] name:@"file_txt" fileName:txtDocuments mimeType:@"text/plain"];
            
            [formData appendPartWithFileData:[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@/%@",strPath,foldDocuments,zipDocuments]] name:@"file_pic" fileName:zipDocuments mimeType:@"application/gzip"];
            
        } progress:^(NSProgress *_Nonnull uploadProgress) {
            //打印下上传进度
            NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_async(queue, ^{
                CGFloat value = 1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
                dispatch_async(dispatch_get_main_queue(), ^{
                    uploadSizeLabel.text = [NSString stringWithFormat:@"已上传：%.2fM",value*[self folderSizeAtPath:[NSString stringWithFormat:@"%@/%@",strPath,foldDocuments]]];
                    [_progressView setProgress:value animated:YES];
                });
            });
            
        } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
            
            [_progressView removeFromSuperview];
            [_bgView removeFromSuperview];
            
            NSString *strPath=[NSString stringWithFormat:@"%@/Documents/taizhan",NSHomeDirectory()];
          
            NSString *savestrPath=[NSString stringWithFormat:@"%@/Documents/taizhansaved",NSHomeDirectory()];
            NSLog(@"savePath:%@",savestrPath);
            [[NSFileManager defaultManager] createDirectoryAtPath:savestrPath withIntermediateDirectories:YES attributes:nil error:nil];
//            for (NSString * value in [_deleteDict allValues]) {
       
            NSArray *documentList2 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strPath error:nil];
            for (NSInteger i=0; i<documentList2.count; i++) {
                if ([documentList2[i] hasPrefix:_stationModel.stationName]) {
                    NSLog(@"%@",documentList2[i]);
                    [[NSFileManager defaultManager] copyItemAtPath:[NSString stringWithFormat:@"%@/%@",strPath,documentList2[i]] toPath:[NSString stringWithFormat:@"%@/%@",savestrPath,documentList2[i]] error:nil];
                    [[NSFileManager defaultManager]  removeItemAtPath:[NSString stringWithFormat:@"%@/%@",strPath,documentList2[i]] error:nil];
//                    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",strPath,value] error:nil];
                }
            }
//            }

            //上传成功
            [self showAlert:@"提交成功" duration:1.0 IsSubmited:YES];

        } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
            //请求失败
            [self showAlert:@"提交失败" duration:1.0 IsSubmited:NO];
            
        }];
        
        [task resume];
        
   
    }
}

//获取单个文件的大小
- (long long)fileSizeAtPath:(NSString*)filePath {
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//获取整个文件夹的大小
- (float )folderSizeAtPath:(NSString*)folderPath {
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    return folderSize/(1024.0*1024.0);
    
}

//设置弹出提示
- (void)showProgress:(NSString *)startString duration:(CGFloat)duration {
    
    _hud = [[MBProgressHUD alloc] init];
    _hud.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    [self.view addSubview:_hud];
    _hud.animationType = MBProgressHUDAnimationZoom;
    _hud.label.text = startString;
    _hud.removeFromSuperViewOnHide = YES;
    [_hud showAnimated:NO];
    [_hud hideAnimated:YES afterDelay:duration];
    
}

//弹出提示框
- (void)showAlert:(NSString *)message duration:(CGFloat)duration IsSubmited:(BOOL)isSubmited {
    
    _hud = [[MBProgressHUD alloc] init];
    _hud.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    [[UIApplication sharedApplication].keyWindow addSubview:_hud];
    _hud.animationType =MBProgressHUDAnimationZoom;
    _hud.mode = MBProgressHUDModeText;
    _hud.label.text = message;
    _hud.label.numberOfLines = 0;
    _hud.label.font = [UIFont systemFontOfSize:12];
    _hud.removeFromSuperViewOnHide = YES;
    [_hud showAnimated:NO];
    [_hud hideAnimated:YES afterDelay:duration];
    if (isSubmited) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

//点击保存按钮
- (void)saveClick {
    
    if (_normalTableView.headView.personTextField.text.length == 0 || [_normalTableView.photoTagArray containsObject:@-1] ){
        
        [self showAlert:@"请填写维护人员和添加图片" duration:1.5 IsSubmited:NO];
        self.isSaved = NO;
        
    }else if ([_normalTableView.headView.personTextField.text hasPrefix:@" "] || [_normalTableView.photoTagArray containsObject:@-1]) {
        
        [self showAlert:@"请填写维护人员和添加图片" duration:1.5 IsSubmited:NO];
        self.isSaved = NO;
        
    }else{
        
        self.isSaved = YES;
//        [self showProgress:@"已保存" duration:1.0];
        
        NSString *strPath=[NSString stringWithFormat:@"%@/Documents/taizhan",NSHomeDirectory()];
        NSArray *documentList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strPath error:nil];
        for (NSInteger i=0; i<documentList.count; i++) {
            if ([documentList[i] hasPrefix:_stationModel.stationName]) {
                [[NSFileManager defaultManager]  removeItemAtPath:[NSString stringWithFormat:@"%@/%@",strPath,documentList[i]] error:nil];
            }
        }
        
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"YYYYMMddHHmmss"];
        NSString * dateTime = [formatter stringFromDate:date];
        
        NSString *strGeneralPath=[NSString stringWithFormat:@"%@/Documents/taizhan",NSHomeDirectory()];
        [[NSFileManager defaultManager] createDirectoryAtPath:strGeneralPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",strGeneralPath);
        
        NSString *strFinalPath=[NSString stringWithFormat:@"%@/%@%@",strGeneralPath,_stationModel.stationName,dateTime];
        [[NSFileManager defaultManager] createDirectoryAtPath:strFinalPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",strFinalPath);
        
        NSString * filePath = [NSString stringWithFormat:@"%@/%@%@.txt",strFinalPath,self.stationModel.stationName,dateTime];
        NSFileManager *fileManager =[NSFileManager defaultManager];
        NSArray * titleArray = @[@"先前状态：",@"运维措施：",@"运维结果："];
        NSArray * firstArray = @[@"蓄电池",@"采集器"];
        NSString * unNormalData = @"";
        NSString * normalData = @"";
        for (NSInteger i=0; i<_unNormalTableView.unNormalArray.count; i++) {
            for (NSInteger j = 0; j<[_unNormalTableView.unNormalArray[i] count]; j++) {
                unNormalData = [unNormalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",[_unNormalTableView.textArray[i] substringFromIndex:2],titleArray[j],_unNormalTableView.unNormalArray[i][j]]];
            }
        }
        for (NSInteger i=0; i<_normalTableView.dataArray.count; i++) {
            for (NSInteger j=0; j<[_normalTableView.dataArray[i] count]; j++) {
                
                if (i == 0&&j == 0) {
                    normalData = [normalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",firstArray[i],titleArray[j],_normalTableView.batteryTextField.text]];
                }else if (i == 1&&j == 0){
                    normalData = [normalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",firstArray[i],titleArray[j],_normalTableView.signalTextField.text]];
                }else{
                    normalData = [normalData stringByAppendingString:[NSString stringWithFormat:@"%@%@%@\r\n",firstArray[i],titleArray[j],_normalTableView.dataArray[i][j]]];
                }
            }
        }
        
        if ([_stationModel.stationStatus isEqualToString:@"0"]||[_stationModel.stationStatus isEqualToString:@"3"]) {
            
            _uploadData = [NSString stringWithFormat:@"任务类型：2"];
            
        }
        else{
            _uploadData = [NSString stringWithFormat:@"任务类型：1"];
        }
        _uploadData = [NSString stringWithFormat:@"%@\r\n%@%@\r\n台站号：%@\r\n%@%@\r\n%@%@\r\n%@%@备注：%@\r\n图片：",_uploadData,_normalTableView.headView.nameLabel.text,_normalTableView.headView.stationName.text,_normalTableView.headView.stationNumber.text,_normalTableView.headView.datelabel.text,_normalTableView.headView.dateTimeLabel.text,_normalTableView.headView.personlabel.text,_normalTableView.headView.personTextField.text,normalData,unNormalData,_normalTableView.remarkTextField.text];
        
        for (NSInteger i = 0; i<_normalTableView.photoTagArray.count; i++) {
            if ([_normalTableView.photoTagArray[i] integerValue]!=-1) {
                
                NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
                
                NSString * imageString = [NSString stringWithFormat:@"%.f.JPEG|",interval];
                [_uploadData stringByAppendingString:imageString];
                _uploadData = [NSString stringWithFormat:@"%@%@",_uploadData,imageString];
                
                UIImage * originImage = _normalTableView.photoArray[i];
                if (originImage.size.width>=originImage.size.height) {
                    [UIImageJPEGRepresentation([self OriginImage:originImage scaleToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT/2)], 1.0)writeToFile: [NSString stringWithFormat:@"%@/%.f.JPEG",strFinalPath,interval] atomically:YES];
                }else{
                    [UIImageJPEGRepresentation([self OriginImage:originImage scaleToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)], 1.0)writeToFile: [NSString stringWithFormat:@"%@/%.f.JPEG",strFinalPath,interval] atomically:YES];
                }
                
            }
        }
        _uploadData = [NSString stringWithFormat:@"%@\r\n图片类型：",_uploadData];
        for (NSInteger i = 0; i<_normalTableView.photoTagArray.count; i++) {
            if ([_normalTableView.photoTagArray[i] integerValue]!=-1) {
                
                NSString * typeString = [NSString stringWithFormat:@"%@|",_normalTableView.titleArray[i]];
                [_uploadData stringByAppendingString:typeString];
                
                _uploadData = [NSString stringWithFormat:@"%@%@",_uploadData,typeString];
                
            }
        }
        _zipper = [[ZipArchive alloc]init];
        [_zipper CreateZipFile2:[NSString stringWithFormat:@"%@/%@%@.zip",strFinalPath,_stationModel.stationName,dateTime]];
        
        NSArray *fileList = [fileManager contentsOfDirectoryAtPath:strFinalPath error:nil];
        for (NSInteger i=0; i<fileList.count; i++) {
            
            NSString * str = [fileList[i] substringFromIndex:[fileList[i] length]-4];
            if ([str isEqualToString:@"JPEG"]) {
                [_zipper addFileToZip:[NSString stringWithFormat:@"%@/%@",strFinalPath,fileList[i]] newname:fileList[i]];
                [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",strFinalPath,fileList[i]] error:nil];
            }
        }
        [_zipper CloseZipFile2];
        
        

        
        [fileManager createFileAtPath:filePath contents:[_uploadData dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
        
         [self showAlert:@"保存成功" duration:1.0 IsSubmited:YES];
    }
}

//缩放图片
- (UIImage*) OriginImage:(UIImage *)image scaleToSize:(CGSize)size {
    
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

#pragma 自定义delegate

//将collectViewCell值转过来
- (void)jumptovc:(NSInteger)tag {
    
    self.cellTag = tag;
    self.picker = [[UIImagePickerController alloc]init];
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            self.picker.delegate=self;
            [self presentViewController:self.picker animated:YES completion:nil];
        }
        else {
            NSLog(@"不支持相机");
        }
    }];
    
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"从相册中选择照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            
            self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            self.picker.delegate=self;
            [self presentViewController:self.picker animated:YES completion:nil];
        }
    }];
    
    [alert addAction:cancel];
    [alert addAction:camera];
    [alert addAction:photo];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma UIimagePicker - Delegate
- (NSString *)getEndTime{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSString *endTime = [dateFormatter stringFromDate:date];
    return endTime;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *shuiyinImage = [self addWatemarkTextAfteriOS7_WithLogoImage:[self OriginImage:image scaleToSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)] watemarkText:[NSString stringWithFormat:@"%@\n%@",[self getEndTime],_currentLocation]];
    
 
    [_normalTableView.photoArray replaceObjectAtIndex:self.cellTag withObject:shuiyinImage];
    [_normalTableView.photoTagArray replaceObjectAtIndex:self.cellTag withObject:[NSString stringWithFormat:@"%i",self.cellTag]];
    [_normalTableView reloadData];
}

- (UIImage *)addWatemarkTextAfteriOS7_WithLogoImage:(UIImage *)logoImage watemarkText:(NSString *)watemarkText{
    int w = logoImage.size.width;
    int h = logoImage.size.height;
    UIGraphicsBeginImageContext(logoImage.size);
    [[UIColor whiteColor] set];
    [logoImage drawInRect:CGRectMake(0, 0, w, h)];
    UIFont * font = [UIFont systemFontOfSize:18.0];
    [watemarkText drawInRect:CGRectMake(10, h-h/9,w/2, h/9) withAttributes:@{NSFontAttributeName:font,NSForegroundColorAttributeName:[UIColor whiteColor]}];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
